package org.sunspotworld;

import com.sun.spot.io.j2me.radiogram.Radiogram;
import com.sun.spot.io.j2me.radiogram.RadiogramConnection;
import java.io.IOException;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;

/**
 *
 * @author Dani
 */
public class Connection{
    private RadiogramConnection clientConn, serverConn;
    private String adress;
    private int portNumber;
    private boolean open = false;

    Connection(String addr, int p){
        adress = addr;
        portNumber = p;
    }

    public void open(String addr, int p){
        init(p, addr);
    }

    public String getAddress(){
        return adress;
    }

    public void init(int port, String addr){

        String clientUrl = "radiogram://" + addr + ":" + port;
        String serverUrl = "radiogram://:" + port;

        try {
            clientConn = (RadiogramConnection)Connector.open(clientUrl);
            serverConn = (RadiogramConnection)Connector.open(serverUrl);
        } catch(ConnectionNotFoundException cnfe) {
            System.out.println("Connection not found");
            cnfe.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        open = true;
    }

    public void sendMessage(String message) throws IOException{
        Datagram datagram = clientConn.newDatagram(clientConn.getMaximumLength());
        datagram.writeUTF(message);
        clientConn.send(datagram);
    }

    public String receiveMessage()throws IOException{
        String message = "";
        Datagram datagram = serverConn.newDatagram(serverConn.getMaximumLength());
        serverConn.receive(datagram);
        message = datagram.readUTF();
       
        return message;
    }

    public void close(){
          try {
            serverConn.close();
            clientConn.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        open = false;
    }

    public int getPortNumber() {
        return portNumber;
    }

    public void setPortNumber(int portNumber) {
        this.portNumber = portNumber;
    }

    public boolean isOpen() {
        return open;
    }

    public void setOpen(boolean open) {
        this.open = open;
    }

    public boolean hasMessage() throws IOException {
        return serverConn.packetsAvailable();
    }
}